You created a game that is more popular than Angry Birds.
Each round, players receive a score between 0 and 100, which you use to rank them from highest to lowest. So far you're using an algorithm that sorts in time, but players are complaining that their rankings aren't updated fast enough. You need a faster sorting algorithm.
Write a function that takes:
and returns a sorted list of scores in less than time.
For example:
unsorted_scores = [37, 89, 41, 65, 91, 53]
HIGHEST_POSSIBLE_SCORE = 100
# Returns [91, 89, 65, 53, 41, 37]
sort_scores(unsorted_scores, HIGHEST_POSSIBLE_SCORE)
We’re defining as the number of unsorted_scores because we’re expecting the number of players to keep climbing.
And, we'll treat highest_possible_score as a constant instead of factoring it into our big O time and space costs because the highest possible score isn’t going to change. Even if we do redesign the game a little, the scores will stay around the same order of magnitude.
We use counting sort.
def sort_scores(unsorted_scores, highest_possible_score):
# List of 0s at indices 0..highest_possible_score
score_counts = [0] * (highest_possible_score+1)
# Populate score_counts
for score in unsorted_scores:
score_counts[score] += 1
# Populate the final sorted list
sorted_scores = []
# For each item in score_counts
for score in range(len(score_counts) - 1, -1, -1):
count = score_counts[score]
# For the number of times the item occurs
for time in range(count):
# Add it to the sorted list
sorted_scores.append(score)
return sorted_scores
time and space, where is the number of scores.
Wait, aren't we nesting two loops towards the bottom? So shouldn't it be time? Notice what those loops iterate over. The outer loop runs once for each unique number in the list. The inner loop runs once for each time that number occurred.
So in essence we're just looping through the numbers from our input list, except we're splitting it into two steps: (1) each unique number, and (2) each time that number appeared.
Here's another way to think about it: in each iteration of our two nested loops, we append one item to sorted_scores. How many numbers end up in sorted_scores in the end? Exactly how many were in our input list! .
If we didn't treat highest_possible_score as a constant, we could call it and say we have time and space.
Note that by optimizing for time we ended up incurring some space cost! What if we were optimizing for space?
We chose to generate and return a separate, sorted list. Could we instead sort the list in place? Does this change the time complexity? The space complexity?
Do you have an answer?
Wanna review this one again later? Or do you feel like you got it all?
Mark as done Pin for review laterReset editor
Powered by qualified.io